package com.xiaoliang.controller;

import com.xiaoliang.entry.Product;
import com.xiaoliang.service.impl.ProductServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.HashMap;

/**
 * @author XIAOLIANG
 * @ClassName CartController.java
 * @Description TODO
 * @createTime 2021年03月03日 09:36:00
 */
@Controller
@RequestMapping("/cart")
public class CartController {

	ProductServiceImpl productService = new ProductServiceImpl();

	@RequestMapping("/addCart/{id}")
	public String addCart(@PathVariable("id") Integer id, HttpSession session){
		HashMap<Integer, Product> cart;
		if (session.getAttribute("cart")==null){
			cart = new HashMap<Integer, Product>();
		}else {
			cart = (HashMap<Integer, Product>) session.getAttribute("cart");
		}

		Product product;

		if (cart.containsKey(id)){  //购物车中该商品已经存在
			product = cart.get(id);
			product.setAccount(product.getAccount()+1);  //数量加1
			session.setAttribute("msg",product.getName()+"商品已在购物车中 数量加1 !");
		}else {                 //该商品并不在购入车中
			product = productService.selectOneById(id);

			if (product!=null){
				product.setAccount(1);    //购物车中的数量设置为1

				cart.put(id,product);
				session.setAttribute("msg",product.getName()+"添加购物车成功!");

			}else {
				session.setAttribute("msg","添加购物车失败! 商品不存在!");
			}
		}

		session.setAttribute("cart",cart);   //将修改后的购物车数据 加入session 更新数据

//		String queryString = (String) session.getAttribute("queryString"); //拿到上一次 访问 Productlist 页面的地址的请求参数 实现带参请求

		return "redirect:/product/queryList";

		}
    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable("id") Integer id,HttpSession session){
		HashMap<Integer,Product> cart = (HashMap<Integer, Product>) session.getAttribute("cart");

		if (cart.containsKey(id)){
			session.setAttribute("msg",cart.get(id).getName()+"已经从购物车中删除");
			cart.remove(id);
		}else {
			session.setAttribute("msg","删除失败 ,该商品已经不存在购物车中");
		}


		return "redirect:/cart/cartList.jsp";



	}

	@RequestMapping("/UpdateCount/{type}/{id}")
	public String increase(@PathVariable("type") String type,@PathVariable("id")Integer id,HttpSession session){
		HashMap<Integer, Product> cart = (HashMap<Integer, Product>) session.getAttribute("cart");

		if (cart.containsKey(id)){
			Product product = cart.get(id);
			int account = product.getAccount();
			if ("reduce".equals(type)){  //减少的操作
				if (account==1){
					session.setAttribute("msg","数量为1 不能再减少");
				}else {
					product.setAccount(account-1);
					session.setAttribute("cart",cart);  //更新数据
				}

			}else {
				product.setAccount(account+1);
			}

		}else {

			session.setAttribute("msg","修该数量失败,该商品已经不再购物车中!");

		}

		return "redirect:/cart/cartList.jsp";


	}






}
